package com.gin.no_gay_alliance.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.viewbinding.ViewBinding;
import androidx.viewpager2.widget.ViewPager2;

import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.base.ViewBindProvider;
import com.gin.no_gay_alliance.enums.MessageWhat;
import com.gin.no_gay_alliance.utils.MenuUtils;
import com.gin.no_gay_alliance.utils.MyHandler;
import com.gin.no_gay_alliance.utils.ReflectUtils;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * ViewBinding模式下的基础活动
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/8/24 15:30
 **/
public abstract class BaseBindingActivity<T extends ViewBinding> extends AppCompatActivity implements MyHandler.Callback, ViewBindProvider<T>, ActivityResultCallback<ActivityResult>, View.OnClickListener, TabLayoutMediator.TabConfigurationStrategy {
    /**
     * 标题字段
     */
    public static final String INTENT_KEY_TITLE = "title";
    protected final String TAG = this.getClass().getSimpleName();
    protected T b;
    protected MyHandler handler;
    protected Toolbar toolbar;
    /**
     * 活动启动器,用于在需要活动返回处理结果时
     */
    ActivityResultLauncher<Intent> launcher;

    /**
     * 解析意图
     *
     * @param intent 意图
     */
    protected abstract void handleIntent(Intent intent);

    /**
     * onCreate中的后续操作
     */
    protected abstract void onCreate();

    /**
     * 装载右上角菜单
     *
     * @param menu         菜单
     * @param menuInflater 菜单渲染器
     */
    protected abstract void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater);

    /**
     * 处理启动器启动的活动返回的结果
     *
     * @param activityResult 结果
     */
    @Override
    public void onActivityResult(ActivityResult activityResult) {

    }

    /**
     * 配置 TabLayout
     *
     * @param tab      标签
     * @param position 位置
     */
    @Override
    public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {

    }

    /**
     * 处理消息
     *
     * @param message 消息
     * @return 是否消耗该消息
     */
    @Override
    public boolean handleMessage(@NonNull Message message) {
        // 设置toolbar的标题
        if (message.what == MessageWhat.UPDATE_TOOLBAR_TITLE.ordinal()) {
            setToolbarTitle(message.obj.toString());
            return true;
        }
        return false;
    }

    /**
     * 反射生成ViewBinding对象
     *
     * @param inflater  渲染器
     * @param container 容器(Fragment用)
     * @return ViewBinding
     */
    @Override
    public T createViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) {
        try {
            ParameterizedType parameterizedType = ReflectUtils.findParameterizedType(getClass());
            if (parameterizedType != null) {
                Type type = parameterizedType.getActualTypeArguments()[0];
                if (type instanceof Class<?>) {
                    Class<?> clazz = ((Class<?>) type);
                    Method method = clazz.getMethod("inflate", LayoutInflater.class);
                    return (T) method.invoke(clazz, inflater);
                } else {
                    System.out.println("type = " + type);
                }
            }
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    /**
     * 如果布局中直接有toolbar, 在此提供, 如果使用Fragment布局中的toolbar,Fragment渲染完成后调用 setToolbar 方法装载
     *
     * @return toolbar toolbar
     */
    protected Toolbar initToolbar() {
        return null;
    }

    /**
     * 点击事件统一配置
     *
     * @param v 被点击的view
     */
    @Override
    public void onClick(View v) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.onDestroy();
            handler = null;
        }
    }

    /**
     * 当handler存在时，使用它执行 Runnable
     *
     * @param runnable
     */
    public final void ui(Runnable runnable) {
        if (handler == null) {
            return;
        }
        handler.post(runnable);
    }

    /**
     * 当handler存在时，使用它执行 Runnable
     *
     * @param runnable
     * @param delayMillis
     */
    public final void uiDelayed(Runnable runnable, long delayMillis) {
        if (handler == null) {
            return;
        }
        handler.postDelayed(runnable, delayMillis);
    }

    /**
     * 关联TabLayout 和 ViewPager2
     *
     * @param tabLayoutMediator tabLayoutMediator
     * @param tabLayout         tabLayout
     * @param vp2               ViewPager2
     * @return TabLayoutMediator
     */
    protected final TabLayoutMediator attachTabLayout(TabLayoutMediator tabLayoutMediator, TabLayout tabLayout, ViewPager2 vp2) {
        // 如果已存在
        if (tabLayoutMediator != null) {
            //取消关联
            tabLayoutMediator.detach();
        }
        // 如果不存在，使用后续参数执行关联
        tabLayoutMediator = new TabLayoutMediator(tabLayout, vp2, this);
        tabLayoutMediator.attach();
        return tabLayoutMediator;
    }

    /**
     * 获取当前activity中的指定位置的子fragment
     *
     * @param position 位置
     * @return Fragment
     */
    public final Fragment getCurrentFragment(int position) {
        return getSupportFragmentManager().findFragmentByTag("f" + position);
    }

    @Override
    protected final void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(MyApplication.app.managerFactory.getThemeManager().getThemeResId());
        // 装载ViewBinding对象
        b = createViewBinding(LayoutInflater.from(this), null);
        if (b != null) {
            setContentView(b.getRoot());
        }
        // 初始化handler
        handler = new MyHandler(this, this);
        // 装载toolbar
        setToolbar(initToolbar());
        // 解析意图
        handleIntent(getIntent());
        launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), this);
        // 后续操作
        onCreate();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 设置临时标题
        Intent intent = getIntent();
        String title = intent.getStringExtra(INTENT_KEY_TITLE);
        if (title != null) {
            setToolbarTitle(title);
        }
    }

    /**
     * 当handler存在时，使用它发送消息
     *
     * @param message
     */
    public final void toast(String message) {
        if (handler == null) {
            return;
        }
        handler.toast(message);
    }

    /**
     * 当handler存在时，使用它发送消息
     *
     * @param message
     */
    public final void toastLong(String message) {
        if (handler == null) {
            return;
        }
        handler.toastLong(message);
    }

    /**
     * 配置右上角菜单
     *
     * @param menu 菜单
     * @return 是否显示菜单
     */
    @Override
    public final boolean onCreateOptionsMenu(Menu menu) {
        // 强制显示菜单图标
        MenuUtils.showMenuIcon(menu);
        // 装载右上角菜单
        onCreateOptionsMenu(menu, getMenuInflater());
        return super.onCreateOptionsMenu(menu);
    }


    /**
     * 提供给子组件获取handler
     *
     * @return handler
     */
    public final MyHandler getHandler() {
        return handler;
    }

    /**
     * 装载toolbar
     *
     * @param toolbar toolbar
     */
    public final void setToolbar(Toolbar toolbar) {
        if (toolbar != null) {
            this.toolbar = toolbar;
            setSupportActionBar(toolbar);
            toolbar.setNavigationOnClickListener(v -> finish());
        }
    }

    /**
     * 设置toolbar的标题
     *
     * @param title 标题
     */
    public final void setToolbarTitle(String title) {
        if (toolbar != null) {
            Log.d(this.getClass().getSimpleName(), "设置Toolbar标题: " + title);
            toolbar.setTitle(title);
        } else {
            Log.w(this.getClass().getSimpleName(), "未装载Toolbar");
        }
    }
}
